package com.ruoyi.car.controller;

import com.ruoyi.car.domain.CarType;
import com.ruoyi.car.domain.vo.CarTypeOrderCountVo;
import com.ruoyi.car.domain.vo.HomeDashboardVo;
import com.ruoyi.car.service.*;
import com.ruoyi.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 首页接口
 * dashboard
 */
@Slf4j
@RestController
@RequestMapping("/car/home")
public class HomeController {
    @Autowired
    private IWxUserService wxUserService;
    @Autowired
    private ICarTestDriveService carTestDriveService;
    @Autowired
    private ICarOrderService carOrderService;
    @Autowired
    private ICarGoodsService carGoodsService;
    @Autowired
    private ICarTypeService carTypeService;

    @GetMapping(value = "/dashboard")
    public R<HomeDashboardVo> dashboard() {
        HomeDashboardVo vo = new HomeDashboardVo();
        vo.setUserCount(wxUserService.countRegister());
        vo.setDriveCount(carTestDriveService.countAll());
        vo.setOrderCount(carOrderService.countAll());
        vo.setGoodsCount(carGoodsService.countAll());
        fillCarTypeOrderCountList(vo.getCarTypeNameList(), vo.getCarTypeOrderCountValueList());
        vo.setCarOrderWayCountList(carOrderService.countByWay());
        return R.ok(vo);
    }

    private void fillCarTypeOrderCountList(List<String> carTypeNameList, List<Integer> carTypeOrderCountValueList) {
        List<CarType> carTypes = carTypeService.selectCarTypeList(new CarType());
        List<CarTypeOrderCountVo> carTypeOrderCountVos = carOrderService.countByCarType();
        Map<Long, Integer> typeIdCount = CollectionUtils.isNotEmpty(carTypeOrderCountVos)
                ? carTypeOrderCountVos
                .stream().collect(Collectors.toMap(CarTypeOrderCountVo::getTypeId, CarTypeOrderCountVo::getOrderCount))
                : new HashMap<>();
        for (CarType carType : carTypes) {
            carTypeNameList.add(carType.getTypeName());
            carTypeOrderCountValueList.add(typeIdCount.getOrDefault(carType.getId(), 0));
        }
    }

}
